package com.sgb.kjwl.view.ui.adapter.self.order;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sgb.kjwl.R;
import com.sgb.kjwl.model.entity.shopping.PurchasingTypeEntity;
import com.sgb.kjwl.model.entity.shopping.ShoppingCarResponse;
import com.swgk.core.util.UiUtil;
import com.sgb.member.weight.NumberInputFilter;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ResolutionUtil;


import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述：核对订单-商品1级适配器
 *
 * @author qiangHeNoo
 * <p>
 * 时间： 2021.04.27
 */
public class CheckParentOrderListAdapter extends BaseQuickAdapter<ShoppingCarResponse, BaseViewHolder> {

    private final Activity context;
    private final String FLOG_O_0 = "0.0";
    private final String FLOG_O_point = "0.";
    private final String FLOG_O_0_0 = "0.00";
    private final String FLOG_O = "0";
    private final String FLOG_1 = "1";
    private final String FLOG_2 = "2";

    public CheckParentOrderListAdapter(Context context, @Nullable List<ShoppingCarResponse> data) {
        super(R.layout.item_parent_check_order, data);
        this.context = (Activity) context;
    }

    @Override
    protected void convert(BaseViewHolder helper, final ShoppingCarResponse item) {
        AtomicInteger payPosition = new AtomicInteger();
        AtomicInteger countPosition = new AtomicInteger();
        AtomicInteger procurementMethodPosition = new AtomicInteger();
        AtomicInteger receivingPosition = new AtomicInteger();
        AtomicInteger loadingPosition = new AtomicInteger();
        AtomicInteger unloadingPosition = new AtomicInteger();
        AtomicInteger installationPosition = new AtomicInteger();
        ShoppingCarResponse.OtherInfo otherInfo = item.getOtherInfos();
        PurchasingTypeEntity typeEntity = item.getPurchasingTypeEntity();
        if (otherInfo == null) {
            otherInfo = new ShoppingCarResponse.OtherInfo();
            item.setOtherInfos(otherInfo);
        }
        helper.setText(R.id.tv_store_name, item.getCompanyName());
        RecyclerView rv = helper.getView(R.id.rv_item);
        rv.setLayoutManager(new LinearLayoutManager(UiUtil.getContext()));
        List<ShoppingCarResponse.ItemsData> dataBeans = item.getItems();
        CheckChildOrderListAdapter adapterChild = new CheckChildOrderListAdapter(dataBeans);
        rv.setAdapter(adapterChild);
        TextView tvAction = helper.getView(R.id.tv_action);
        LinearLayout linearLayout = helper.getView(R.id.ll_more_information);
        RelativeLayout relativeLayout = helper.getView(R.id.rl_showing_more);
        tvAction.setOnClickListener(v -> setActionTextAndDrawable(tvAction, relativeLayout, linearLayout));
        if (typeEntity != null && typeEntity.getTransport() != null && typeEntity.getTransport().size() > 0) {
            ((TextView) helper.getView(R.id.tv_logistics_services)).setText(typeEntity.getTransport().get(0).getName());
            otherInfo.setTransport(Integer.parseInt(typeEntity.getTransport().get(0).getNo()));
        } else {
            ((TextView) helper.getView(R.id.tv_logistics_services)).setText("供应商配送");
            otherInfo.setTransport(1);
        }
        ShoppingCarResponse.OtherInfo finalOtherInfo = otherInfo;
        final LinearLayout payMethod = helper.getView(R.id.pay_method);
        final ImageView imgTip1 = helper.getView(R.id.img_tip1);
        final ImageView arrow_right_img = helper.getView(R.id.arrow_right_img);
        final TextView tvPayMethod = helper.getView(R.id.tv_pay_method);
        imgTip1.setOnClickListener(v -> {
            new RoundDialog.Builder(context)
                    .title("付款方式说明")
                    .content("1.银行转账：支持采购商通过线下转账的方式向商家银行账户付款，由于款项是直接到账商家银行账户，风险较高，请谨慎选择。\n" +
                            "2.网银支付：平台担保交易，采购商通过网银支付到平台暂时冻结资金，签收订单后，解冻资金到商家账户，安全有保障，建议选择。")
                    .confirm("知道了")
                    .singleBtn(true)
                    .contentGravity(Gravity.CENTER)
                    .cancelable(true)
                    .show();
        });
        if (typeEntity != null && typeEntity.getPaymentMethod() != null && typeEntity.getPaymentMethod().size() > 0) {
            if (FLOG_1.equals(item.getIsOpenAccount())) {
                if (item.getPaymentMethod() == 0) {
                    tvPayMethod.setText("网银支付");
                    payPosition.set(getNormalPosition(typeEntity.getPaymentMethod(), "网银支付"));
                } else if (item.getPaymentMethod() == 1) {
                    tvPayMethod.setText("银行转账");
                    payPosition.set(getNormalPosition(typeEntity.getPaymentMethod(), "银行转账"));
                }
            } else {
                tvPayMethod.setText("银行转账");
                payPosition.set(getNormalPosition(typeEntity.getPaymentMethod(), "银行转账"));
            }
            item.setPaymentMethod(Integer.parseInt(typeEntity.getPaymentMethod().get(payPosition.get()).getNo()));
            payMethod.setOnClickListener(v -> {
                OptionsPickerView businessOption = new OptionsPickerBuilder(context, (options1, options2, options3, v1) -> {
                    if (!FLOG_1.equals(item.getIsOpenAccount()) && "网银支付".equals(typeEntity.getPaymentMethod().get(options1).getName())) {
                        MToast.showToast(context, "该商家开通在线支付后，才可使用网银支付");
                    } else {
                        String content = typeEntity.getPaymentMethod().get(options1).getName();
                        tvPayMethod.setText(content);
                        payPosition.set(options1);
                        item.setPaymentMethod(Integer.parseInt(typeEntity.getPaymentMethod().get(options1).getNo()));
                    }
                }).setLineSpacingMultiplier(2.2f)
                        .setCancelColor(0xFF666666)
                        .setTitleColor(0xFF969696)
                        .setSubCalSize(15)
                        .setTitleSize(15)
                        .setContentTextSize(15)
                        .build();
                businessOption.setPicker(typeEntity.getPaymentMethod());
                businessOption.setSelectOptions(payPosition.get());
                businessOption.setTitleText("付款方式");
                businessOption.show();
            });
        } else {
            arrow_right_img.setVisibility(View.INVISIBLE);
            tvPayMethod.setText("银行转账");
            item.setPaymentMethod(1);
        }
        final ItemInputTextView procurementMethod = helper.getView(R.id.tv_procurement_method);
        if (typeEntity != null && typeEntity.getPurchasingMethod() != null && typeEntity.getPurchasingMethod().size() > 0) {
            if (TextUtils.isEmpty(item.getShowPurchasingMethod()) || FLOG_1.equals(item.getShowPurchasingMethod())) {
                procurementMethod.setContent("直接采购");
                procurementMethodPosition.set(getNormalPosition(typeEntity.getPurchasingMethod(), "直接采购"));
            } else if (FLOG_2.equals(item.getShowPurchasingMethod())) {
                procurementMethod.setContent("合同采购");
                procurementMethodPosition.set(getNormalPosition(typeEntity.getPurchasingMethod(), "合同采购"));
            }
            finalOtherInfo.setPurchasingMethod(Integer.parseInt(typeEntity.getPurchasingMethod().get(procurementMethodPosition.get()).getNo()));
            item.setShowPurchasingMethod(typeEntity.getPurchasingMethod().get(procurementMethodPosition.get()).getNo());
            procurementMethod.setOnWholeItemClickListener(v -> {
                OptionsPickerView businessOption = new OptionsPickerBuilder(context, (options1, options2, options3, v1) -> {
                    String content = typeEntity.getPurchasingMethod().get(options1).getName();
                    procurementMethod.setContent(content);
                    procurementMethodPosition.set(options1);
                    finalOtherInfo.setPurchasingMethod(Integer.parseInt(typeEntity.getPurchasingMethod().get(options1).getNo()));
                    item.setShowPurchasingMethod(typeEntity.getPurchasingMethod().get(options1).getNo());
                }).setLineSpacingMultiplier(2.2f)
                        .setCancelColor(0xFF666666)
                        .setTitleColor(0xFF969696)
                        .setSubCalSize(15)
                        .setTitleSize(15)
                        .setContentTextSize(15)
                        .build();
                businessOption.setPicker(typeEntity.getPurchasingMethod());
                businessOption.setSelectOptions(procurementMethodPosition.get());
                businessOption.setTitleText("采购方式");
                businessOption.show();
            });
        } else {
            procurementMethod.setContent("直接采购");
            procurementMethod.setArrowVisible(false);
            finalOtherInfo.setPurchasingMethod(1);
            item.setShowPurchasingMethod("1");
        }


        final ItemInputTextView countMethod = helper.getView(R.id.tv_pay_count);
        if (typeEntity != null && typeEntity.getPaymentBatch() != null && typeEntity.getPaymentBatch().size() > 0) {
            countMethod.setContent(typeEntity.getPaymentBatch().get(0).getName());
            item.setPayBatch(typeEntity.getPaymentBatch().get(0).getNo());
            countMethod.setOnWholeItemClickListener(v -> {
                OptionsPickerView businessOption = new OptionsPickerBuilder(context, (options1, options2, options3, v1) -> {
                    if (FLOG_O.equals(typeEntity.getPaymentBatch().get(options1).getNo())) {
                        showBatchDialog(item, countMethod);
                    } else {
                        String content = typeEntity.getPaymentBatch().get(options1).getName();
                        countMethod.setContent(content);
                        countPosition.set(options1);
                        item.setPayBatch(typeEntity.getPaymentBatch().get(options1).getNo());
                    }
                }).setLineSpacingMultiplier(2.2f)
                        .setCancelColor(0xFF666666)
                        .setTitleColor(0xFF969696)
                        .setSubCalSize(15)
                        .setTitleSize(15)
                        .setContentTextSize(15)
                        .build();
                businessOption.setPicker(typeEntity.getPaymentBatch());
                businessOption.setSelectOptions(countPosition.get());
                businessOption.setTitleText("支付比例");
                businessOption.show();
            });
        } else {
            countMethod.setArrowVisible(false);
            countMethod.setContent(typeEntity.getPaymentBatch().get(0).getName());
            item.setPayBatch(typeEntity.getPaymentBatch().get(0).getNo());
        }

        final ItemInputTextView receivingMethod = helper.getView(R.id.receiving_method);
        if (typeEntity != null && typeEntity.getReceivingMethod() != null && typeEntity.getReceivingMethod().size() > 0) {
            receivingMethod.setOnWholeItemClickListener(v -> {
                OptionsPickerView businessOption = new OptionsPickerBuilder(context, (options1, options2, options3, v1) -> {
                    if (FLOG_O.equals(typeEntity.getReceivingMethod().get(options1).getNo())) {
                        receivingMethod.setContent("");
                        receivingMethod.setLabelHint("请选择收货方式");
                        finalOtherInfo.setReceivingMethod(0);
                    } else {
                        String content = typeEntity.getReceivingMethod().get(options1).getName();
                        receivingMethod.setContent(content);
                        receivingPosition.set(options1);
                        finalOtherInfo.setReceivingMethod(Integer.parseInt(typeEntity.getReceivingMethod().get(options1).getNo()));
                    }
                }).setLineSpacingMultiplier(2.2f)
                        .setCancelColor(0xFF666666)
                        .setTitleColor(0xFF969696)
                        .setSubCalSize(15)
                        .setTitleSize(15)
                        .setContentTextSize(15)
                        .build();
                businessOption.setPicker(typeEntity.getReceivingMethod());
                businessOption.setSelectOptions(receivingPosition.get());
                businessOption.setTitleText("收货方式");
                businessOption.show();
            });
        } else {
            receivingMethod.setContent("");
            receivingMethod.setLabelHint("请选择收货方式");
            finalOtherInfo.setReceivingMethod(0);
        }

        final ItemInputTextView loadingService = helper.getView(R.id.loading_service);
        if (typeEntity != null && typeEntity.getLoading() != null && typeEntity.getLoading().size() > 0) {
            loadingService.setOnWholeItemClickListener(v -> {
                OptionsPickerView businessOption = new OptionsPickerBuilder(context, (options1, options2, options3, v2) -> {
                    if (FLOG_O.equals(typeEntity.getLoading().get(options1).getNo())) {
                        loadingService.setContent("");
                        loadingService.setLabelHint("请选择装车服务");
                        finalOtherInfo.setLoading(0);
                    } else {
                        String content = typeEntity.getLoading().get(options1).getName();
                        loadingService.setContent(content);
                        loadingPosition.set(options1);
                        finalOtherInfo.setLoading(Integer.parseInt(typeEntity.getLoading().get(options1).getNo()));
                    }
                }).setLineSpacingMultiplier(2.2f)
                        .setCancelColor(0xFF666666)
                        .setTitleColor(0xFF969696)
                        .setSubCalSize(15)
                        .setTitleSize(15)
                        .setContentTextSize(15)
                        .build();
                businessOption.setPicker(typeEntity.getLoading());
                businessOption.setSelectOptions(loadingPosition.get());
                businessOption.setTitleText("装车服务");
                businessOption.show();
            });
        } else {
            loadingService.setContent("");
            loadingService.setLabelHint("请选择装车服务");
            finalOtherInfo.setLoading(0);
        }

        final ItemInputTextView unloadingService = helper.getView(R.id.unloading_service);
        if (typeEntity != null && typeEntity.getUnloading() != null && typeEntity.getUnloading().size() > 0) {
            unloadingService.setOnWholeItemClickListener(v -> {
                OptionsPickerView businessOption = new OptionsPickerBuilder(context, (options1, options2, options3, v3) -> {
                    if (FLOG_O.equals(typeEntity.getUnloading().get(options1).getNo())) {
                        unloadingService.setContent("");
                        unloadingService.setLabelHint("请选择卸车服务");
                        finalOtherInfo.setUnloading(0);
                    } else {
                        String content = typeEntity.getUnloading().get(options1).getName();
                        unloadingService.setContent(content);
                        unloadingPosition.set(options1);
                        finalOtherInfo.setUnloading(Integer.parseInt(typeEntity.getUnloading().get(options1).getNo()));
                    }
                }).setLineSpacingMultiplier(2.2f)
                        .setCancelColor(0xFF666666)
                        .setTitleColor(0xFF969696)
                        .setSubCalSize(15)
                        .setTitleSize(15)
                        .setContentTextSize(15)
                        .build();
                businessOption.setPicker(typeEntity.getUnloading());
                businessOption.setSelectOptions(unloadingPosition.get());
                businessOption.setTitleText("卸车服务");
                businessOption.show();
            });
        } else {
            unloadingService.setContent("");
            unloadingService.setLabelHint("请选择卸车服务");
            finalOtherInfo.setUnloading(0);
        }

        final ItemInputTextView installationService = helper.getView(R.id.installation_service);
        if (typeEntity != null && typeEntity.getInstallService() != null && typeEntity.getInstallService().size() > 0) {
            installationService.setOnWholeItemClickListener(v -> {
                OptionsPickerView businessOption = new OptionsPickerBuilder(context, (options1, options2, options3, v3) -> {
                    if (FLOG_O.equals(typeEntity.getInstallService().get(options1).getNo())) {
                        installationService.setContent("");
                        installationService.setLabelHint("请选择安装服务");
                        finalOtherInfo.setInstallService(0);
                    } else {
                        String content = typeEntity.getInstallService().get(options1).getName();
                        installationService.setContent(content);
                        installationPosition.set(options1);
                        finalOtherInfo.setInstallService(Integer.parseInt(typeEntity.getInstallService().get(options1).getNo()));
                    }
                }).setLineSpacingMultiplier(2.2f)
                        .setCancelColor(0xFF666666)
                        .setTitleColor(0xFF969696)
                        .setSubCalSize(15)
                        .setTitleSize(15)
                        .setContentTextSize(15)
                        .build();
                businessOption.setPicker(typeEntity.getInstallService());
                businessOption.setSelectOptions(installationPosition.get());
                businessOption.setTitleText("安装服务");
                businessOption.show();
            });
        } else {
            installationService.setContent("");
            installationService.setLabelHint("请选择安装服务");
            finalOtherInfo.setInstallService(0);
        }
        helper.setVisible(R.id.image_view, FLOG_1.equals(item.getSelfSupportTag()));
        helper.setText(R.id.tv_total_price, "￥" + UiUtil.getDecimalFormat(calculateTotalPrice(item)));
    }

    @SuppressLint("InflateParams")
    private void showBatchDialog(ShoppingCarResponse item, ItemInputTextView countMethod) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.inputDialog);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_pay_proportion, null);
        TextView tvCancel = view.findViewById(R.id.tv_logout_cancel);
        TextView tvConfirm = view.findViewById(R.id.tv_logout_confirm);
        EditText etValue = view.findViewById(R.id.et_value);
        etValue.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        etValue.setFilters(new NumberInputFilter[]{new NumberInputFilter(100, 0.01, 2)});
        final Dialog alertDialog = builder.setCancelable(false).create();
        tvCancel.setOnClickListener(v -> alertDialog.dismiss());
        tvConfirm.setOnClickListener(v -> {
            String value = etValue.getText().toString().trim();
            if (TextUtils.isEmpty(value) || FLOG_O.equals(value)) {
                MToast.showToast(context, "请输入支付比例");
            } else {
                if (FLOG_O_0.equals(value) || FLOG_O_0_0.equals(value) || FLOG_O_point.equals(value)) {
                    MToast.showToast(context, "请输入大于0，小于等于100的数字");
                    return;
                }
                countMethod.setContent(value + "%支付");
                item.setPayBatch(value);
                alertDialog.dismiss();
            }
        });
        alertDialog.show();
        Objects.requireNonNull(alertDialog.getWindow()).setContentView(view);
        alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

    private double calculateTotalPrice(ShoppingCarResponse item) {
        double totalPrice = 0.00d;
        List<ShoppingCarResponse.ItemsData> dataBeans = item.getItems();
        if (dataBeans != null && dataBeans.size() != 0) {
            for (ShoppingCarResponse.ItemsData itemsData : dataBeans) {
                //需求变更，总价取最优价（price）的总和
                // double realPrice = getRealUnitPrice(itemsData);
                double realPrice = itemsData.getPrice();
                totalPrice = totalPrice + realPrice * itemsData.getItemNum();
            }
        }
        return totalPrice;
    }

    /**
     * 新需求变更，不再使用促销价
     */
    @Deprecated
    private double getRealUnitPrice(ShoppingCarResponse.ItemsData item) {
        double unitPrice = 0.00d;
        if (item.getPromoteStatus() == 2) {
            unitPrice = item.getPromotePrice();
        } else {
            unitPrice = item.getPrice();
        }
        return unitPrice;
    }

    private void setActionTextAndDrawable(TextView tvAction, RelativeLayout relativeLayout, LinearLayout container) {
        String action = tvAction.getText().toString().trim();
        if (action.contains("收起")) {
            tvAction.setText("展开");
            tvAction.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context, R.mipmap.icon_expand), null);
            relativeLayout.setPadding(ResolutionUtil.dp2px(context, 16), ResolutionUtil.dp2px(context, 16), ResolutionUtil.dp2px(context, 16), ResolutionUtil.dp2px(context, 16));
            container.setVisibility(View.GONE);
        } else {
            tvAction.setText("收起");
            tvAction.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context, R.mipmap.icon_up_1), null);
            relativeLayout.setPadding(ResolutionUtil.dp2px(context, 16), ResolutionUtil.dp2px(context, 16), ResolutionUtil.dp2px(context, 16), ResolutionUtil.dp2px(context, 0));
            container.setVisibility(View.VISIBLE);
        }
    }

    private int getNormalPosition(List<PurchasingTypeEntity.PaymentMethod> methods, String name) {
        int index = 0;
        for (int i = 0; i < methods.size(); i++) {
            if (name.equals(methods.get(i).getName())) {
                index = i;
            }
        }
        return index;
    }


}
